package com.dingreading.cloud.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.dingreading.cloud.admin.entity.StoreFollow;
import com.dingreading.cloud.admin.entity.StoreFollowImg;
import com.dingreading.cloud.admin.entity.StoreFollowType;
import com.dingreading.cloud.admin.entity.Stores;
import com.dingreading.cloud.admin.service.StoreFollowImgService;
import com.dingreading.cloud.admin.service.StoreFollowService;
import com.dingreading.cloud.admin.service.StoreFollowTypeService;
import com.dingreading.cloud.admin.service.StoresService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RefreshScope
@RestController
@RequestMapping("/system/storeFollow")
@Api(tags = "总部-门店跟进记录管理")
public class StoreFollowController {

    @Resource
    private StoresService storesService;
    @Resource
    private StoreFollowService storeFollowService;
    @Resource
    private StoreFollowTypeService followTypeService;
    @Resource
    private StoreFollowImgService storeFollowImgService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList")
    public R<Object> pageList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid", required = false) String storeUid,
            @ApiParam(value = "内容/类型") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "来源 1.系统 2.员工") @RequestParam(value = "source", required = false) Integer source,
            @ApiParam(value = "业务展示 0.不展示 1.展示") @RequestParam(value = "operate", required = false) Integer operate,
            @ApiParam(value = "缴费开始日期 yyyy-MM-dd") @RequestParam(value = "beginDate", required = false) String beginDate,
            @ApiParam(value = "缴费结束日期 yyyy-MM-dd") @RequestParam(value = "endDate", required = false) String endDate
    ) {
        Page<StoreFollow> page = storeFollowService.pageList(pageUtil, storeUid, beginDate, endDate, keyword, source, operate);

        List<StoreFollow> list = page.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> followIds = list.stream().map(StoreFollow::getId).collect(Collectors.toList());

            List<StoreFollowImg> fileList = storeFollowImgService.listByFollowIdIn(followIds);
            if (CollectionUtils.isNotEmpty(fileList)) {
                Map<Long, List<StoreFollowImg>> map = fileList.stream()
                        .collect(Collectors.groupingBy(StoreFollowImg::getFollowId, Collectors.toList()));
                for (StoreFollow follow : list) {
                    follow.setImgList(map.get(follow.getId()));
                }
            }
        }

        PageBeanDto data = new PageBeanDto();
        data.setTotal(page.getTotalRow());
        data.setList(page.getRecords());
        return R.ok(data);
    }

    @ApiOperation(value = "按门店uid获取跟进列表")
    @PostMapping(value = "/getList")
    public R<Object> getList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid", required = false) String storeUid,
            @ApiParam(value = "来源 1.系统 2.员工") @RequestParam(value = "source", required = false) Integer source,
            @ApiParam(value = "业务展示 0.不展示 1.展示") @RequestParam(value = "operate", required = false) Integer operate
    ) {
        List<StoreFollow> list = storeFollowService.listByStoreUid(storeUid, source, operate);

        return R.ok(list);
    }

    @ApiOperation(value = "根据id获取信息")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "合同id") @RequestParam(value = "id") Long id
    ) {
        StoreFollow data = storeFollowService.getById(id);
        if (null == data)
            return R.fail("未查询到信息");

        List<StoreFollowImg> imgList = storeFollowImgService.listByFollowId(id);
        if (CollectionUtils.isNotEmpty(imgList))
            data.setImgList(imgList);

        return R.ok(data);
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "创建/更新信息")
    @PostMapping(value = "/newBean", produces = "application/json; charset=UTF-8")
    public R<Object> newBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "跟进内容") @RequestParam(value = "content") String content,
            @ApiParam(value = "跟进时间") @RequestParam(value = "followTime") String followTime,
            @ApiParam(value = "跟进类型uid") @RequestParam(value = "followTypeUid") String followTypeUid,
            @ApiParam(value = "文件地址集合[{id:0,url:''}]") @RequestParam(value = "fileJson", required = false) String fileJson
    ) throws Exception {
        if (StringUtils.isBlank(content))
            return R.fail("请输入跟进内容");
        if (StringUtils.isBlank(followTime))
            return R.fail("请选择跟进时间");

        StoreFollowType followType = followTypeService.getByUid(followTypeUid);
        if (followType == null)
            return R.fail("未查询到跟进类型");

        StoreFollow data = null;
        if (null == id || id <= 0) {
            Stores stores = storesService.getByUid(storeUid);
            if (stores == null)
                return R.fail("未查询到门店");

            data = new StoreFollow();
            data.setAddStaffUid(headStaffUid);
            data.setAddStaffName(headStaffName);
            data.setCorpUid(stores.getCorpUid());
            data.setStoreUid(storeUid);
        } else {
            data = storeFollowService.getById(id);
            if (null == data)
                return R.fail("未查询到合同");
            if (data.getSource().equals(1))
                return R.fail("系统信息，不能操作");
            if (TimeUtil.moreThanDay(data.getAddTime(), 30))
                return R.fail("录入超过30天，不能操作");
        }
        data.setContent(content);
        data.setFollowTime(DateUtil.parseDateFromStr(followTime));
        data.setFollowTypeUid(followType.getUid());
        data.setFollowTypeName(followType.getName());
        data.setSource(followType.getSource());
        data.setOperation(followType.getOperation());
        data.setLastStaffUid(headStaffUid);
        data.setLastStaffName(headStaffName);
        storeFollowService.saveOrUpdate(data);

        // 保存图片
        if (StringUtils.isNotBlank(fileJson)) {
            List<StoreFollowImg> fileList = JSONArray.parseArray(fileJson, StoreFollowImg.class);

            List<Long> ids = new ArrayList<>();
            for (StoreFollowImg file : fileList) {
                if (file.getId() == null || file.getId() <= 0) {
                    file.setFollowId(data.getId());
                    file.setAddStaffUid(headStaffUid);
                    file.setAddStaffName(headStaffName);
                } else {
                    ids.add(file.getId());
                }
            }

            // 先删除不保存的文件
            storeFollowImgService.deleteByFileIdsNotIn(data.getId(), ids);

            storeFollowImgService.saveOrUpdateBatch(fileList);
        }

        return R.ok();
    }

    @ApiOperation(value = "删除")
    @PostMapping(value = "/deleteBean", produces = "application/json; charset=UTF-8")
    public R<Object> deleteBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "合同id") @RequestParam(value = "id") Long id
    ) {
        StoreFollow data = storeFollowService.getById(id);
        if (data == null)
            return R.fail("未查询到信息");
        if (data.getSource().equals(1)) {
            return R.fail("系统信息，不能操作");
        } else {
            boolean b = TimeUtil.moreThanDay(data.getAddTime(), 30);
            if (b)
                return R.fail("录入超过30天，不能操作");
        }

        boolean b = storeFollowService.removeById(id);
        if (!b)
            return R.failDel();

        return R.ok();
    }

    @ApiOperation(value = "上传跟进文件")
    @PostMapping(value = "/uploadFile", produces = "application/json; charset=UTF-8")
    public R<Object> uploadFile(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "文件") @RequestPart(value = "file") MultipartFile file
    ) throws Exception {
        // 上传图片到服务器
        R<String> r = LocalFileUtil.uploadFile(LocalFileUtil.followBaseDir, file);
        if (R.isError(r))
            return R.fail(r.getMsg());

        return R.ok("follow/" + r.getData());
    }

    @ApiOperation(value = "获取可手动加入的跟进类型")
    @PostMapping(value = "/getFollowTypeList")
    public R<Object> getFollowTypeList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName
    ) {
        List<StoreFollowType> list = followTypeService.listBySource();
        return R.ok(list);
    }

}